<template>
	<view>
		<custom-header title="供应商管理" :isConfirm="isComplete" :isProPayContract="isProPayContract" :returnBack="true" @confirm="confirm" :showDelete="showDelete" @delete="onDel" @backStep="backStep" />
		<u-sticky :customNavHeight="height">
			<u-tabs class="tabs" :list="tabsList" @click="onTabClick"
				style="padding: 0 24rpx; background: #fff; z-index: 22; position: sticky; top: 0px"
				:activeStyle="{ color: '#171717', fontSize: '16px', fontWeight: 500 }"
				:inactiveStyle="{ color: '#C6C6C6', fontSize: '16px', fontWeight: 500 }" lineColor="#1E6FFF"></u-tabs>
		</u-sticky>
		<!-- #ifdef APP-PLUS -->
		<view style="height: 40px;"></view>
		<!-- #endif -->
		<view class="task_lists" :style="{ marginTop: '50px' }">
			<collapse name="基础信息" id="outside1" :maxHeight="maxHeight1" :borderRadius="0" :hasIcon="true">
				<view class="listdefault" :id="uId1">
					<view class="action" v-for="(item, index) in basicInfo" :key="index"
						:style="{ width: item.labelWidth + '%' }">
						<view class="list1">{{ item.label }}</view>
						<view class="list2">
							<template v-if="item.key === 'proposer'">
								<custom-select-person disabled v-model="detailData.proposer" />
							</template>
							<template v-else-if="item.key === 'proposerDeptId'">
								<custom-select-depart disabled v-model="detailData.proposerDeptId" />
							</template>
							<template v-else>
								{{ detailData[item.key] }}
							</template>
						</view>
					</view>
				</view>
			</collapse>
			<collapse name="往来单位信息" id="outside2" :maxHeight="maxHeight2" :borderRadius="0" :hasIcon="true">
				<view class="listdefault" :id="uId2">
					<view class="action" v-for="(item, key) in contactUnitInfo" :key="key"
						:style="{ width: item.labelWidth + '%' }">
						<view class="list1">{{ item.label }}</view>
						<view class="list2">
							<template v-if="detailData[item.key]">
								<template v-if="item.key === 'commercialType'">
									<h-dictCode :value="detailData[item.key]" dictName="commercial_type"></h-dictCode>
								</template>
								<template v-else-if="item.key === 'enterpriseType'">
									<h-dictCode :value="detailData[item.key]" dictName="enterprise_type"></h-dictCode>
								</template>
								<template v-else-if="item.key === 'provisionBroad'">
									<custom-dropdown disabled class="w-100" keyName="categoryName" border="none"
										:api="api.queryProvisionBroadList" v-model="detailData[item.key]"
										dataKey="result" />
								</template>
								<template v-else-if="item.key === 'provisionSmall'">
									<custom-select-material-small class="w-100" :muitFlag="true"
										:parentId="detailData.provisionBroad" v-model="detailData[item.key]"
										placeholder="请选择物料小类" border="none" disabled></custom-select-material-small>
								</template>
								<template v-else>
									{{ detailData[item.key] }}
								</template>
							</template>
							<text v-else-if="!detailData[item.key] && item.required && isClick" class="red">{{ item.tipType === 1 ? '请输入' : '请选择' }}{{ item.label }}</text>
						</view>
					</view>
				</view>
				<view slot="handler" class="btn-edit" v-if="showEdit" @click="goEdit(APPTYPE.CONTACTUNIT)">编辑</view>
			</collapse>
			<collapse name="联系人信息" id="outside3" :maxHeight="maxHeight3" :borderRadius="0" :hasIcon="true">
				<view class="collapse_action" :id="uId3">
					<view class="child_action" v-if="childTable.length > 0">
						<block v-for="(value, index) in childTable" :key="index">
							<view class="line" :style="{ height: '2rpx' }"></view>
							<view :class="['listsmall', 'half-width']">
								<view class="action" v-for="(item, key) in childFields" :key="item">
									<view class="list1">{{ key }}</view>
									<view class="list2">{{ value[item] }}</view>
								</view>
							</view>
						</block>
					</view>
					<u-empty v-else mode="data" icon="/static/empty/data.png" :textColor="isClick?'red':'#c0c4cc'" :text="isClick?'请添加联系人信息':''"></u-empty>
				</view>
				<view slot="handler" class="btn-edit" v-if="showEdit" @click="goEdit(APPTYPE.CONTACTS)">编辑</view>
			</collapse>
			<!-- <action-collapse name="联系人信息" :childFields="childFields" id="outside3" :dataSource="childTable"
				:borderRadius="0" :hasIcon="true" empty-text="请添加联系人信息" empty-text-color="red">
				<view slot="handler" class="btn-edit" v-if="showEdit" @click="goEdit(APPTYPE.CONTACTS)">编辑</view>
			</action-collapse> -->
			<default-list name="企业资质材料" :borderRadius="0" :hasIcon="true" id="outside4">
				<view v-for="(item, index) in companyDataInfo" :key="index">
					<view class="file-type">{{ item.label }}</view>
					<file-list :fileList="detailData[item.key]" :empty-text="'请选择' + item.label"
						empty-text-color="red"></file-list>
					<view class="file-type-line" v-if="index !== companyDataInfo.length - 1"></view>
				</view>
				<view slot="handler" class="btn-edit" v-if="showEdit" @click="goEdit(APPTYPE.COMPANYDATA)">编辑</view>
			</default-list>
		</view>
		<collapse name="驳回理由" :borderRadius="0" :hasIcon="true" v-if="detailData.rejectExcuse">
			<view class="reject-reason">{{ detailData.rejectExcuse }}</view>
		</collapse>
		<view style="height: 100px;" v-if="showSave || showDelete"></view>
		<view class="space-x-1 px-1 btn_position" v-if="showSave">
			<template v-if="isProPayContract">
				<u-button type="primary" :plain="true" text="关闭" @click="onClose"
					:disabled="$hasPerm('erpPurchaseSupplier:submit') || isSubmit"></u-button>
				<u-button type="primary" text="提交" @click="onSubmit"
					:disabled="$hasPerm('erpPurchaseSupplier:submit') || isSubmit"></u-button>
			</template>
			<template v-else>
				<u-button type="primary" :plain="true" text="保存" @click="onDraft"
					:disabled="$hasPerm('erpPurchaseSupplier:submit') || isSubmit"></u-button>
				<u-button type="primary" text="提交" @click="onSubmit"
					:disabled="$hasPerm('erpPurchaseSupplier:submit') || isSubmit"></u-button>
			</template>
			
		</view>
		<view class="space-x-1 px-1 btn_position" v-if="showDelete">
			<u-button type="primary" :plain="true" text="编辑" @click="onEdit"
				:disabled="$hasPerm('erpPurchaseSupplier:edit') || isSubmit"></u-button>
			<u-button type="primary" text="提交" @click="onSubmit"
				:disabled="$hasPerm('erpPurchaseSupplier:submit') || isSubmit"></u-button>
		</view>
		<u-toast ref="uToast"></u-toast>
	</view>
</template>
<script>
import APPTYPE from '@/config/appType.js'
import {
	mapState
} from 'vuex'
import moment from 'moment'
import fileList from '@/pages/purchase/components/fileList.vue'
import collapse from '@/pages/purchase/components/collapse.vue'
import defaultList from '@/pages/purchase/components/defaultList.vue'
import {
	queryById,
	childList,
	submit,
	edit,
	add,
	deleteData,
	supplierSubmit
} from '@/api/purchase/ErpPurchaseSupplier.js'
import {
	queryProvisionBroadList,
	queryProvisionSmallList
} from '@/api/purchase/ErpPurchaseCannibalizeForm'
export default {
	data() {
		return {
			api: {
				queryProvisionSmallList,
				queryProvisionBroadList,
			},
			isClick: false,
			isProPayContract: false,
			APPTYPE: APPTYPE,
			tabsList: [{
				name: '基础信息',
				id: 'outside1'
			}, {
				name: '往来单位信息',
				id: 'outside2'
			}, {
				name: '联系人信息',
				id: 'outside3'
			}, {
				name: '企业资质材料',
				id: 'outside4'
			}],
			childTable: [],
			detailData: {
				proposerDeptId: '',
				proposer: '',
				createTime: '',
				enterpriseName: '',
				commercialType: '',
				enterpriseCreditCode: '',
				enterpriseType: '',
				legalRepresentative: '',
				enterpriseAddress: '',
				registerDate: '',
				registerCapital: '',
				bankName: '',
				bankAccountNo: '',
				companyWeb: '',
				provisionBroad: '',
				provisionSmall: '',
				mainBussiness: '',
				legalRepresentativeCard: '',
				bussinessLicense: '',
				supplierCertification: '',
				cooperativeContract: '',
			}, // 详情数据
			basicInfo: [{
				label: '申请部门',
				key: 'proposerDeptId',
				labelWidth: 100
			},
			{
				label: '申请人',
				key: 'proposer',
			},
			{
				label: '申请时间',
				key: 'createTime',
			}
			],
			contactUnitInfo: [{
				label: '企业名称',
				key: 'enterpriseName',
				labelWidth: 100,
				tipType: 1,
				required: true
			},
			{
				label: '商户类型',
				key: 'commercialType',
				tipType: 1,
				required: true
			},
			{
				label: '企业信用代码',
				key: 'enterpriseCreditCode',
				tipType: 1,
				required: true
			},
			{
				label: '企业类型',
				key: 'enterpriseType',
				tipType: 2,
				required: true
			},
			{
				label: '法定代表人',
				key: 'legalRepresentative',
				tipType: 1,
				required: true
			},
			{
				label: '企业地址',
				key: 'enterpriseAddress',
				labelWidth: 100,
				tipType: 1,
				required: true
			},
			{
				label: '公司注册时间',
				key: 'registerDate',
				tipType: 2,
				required: true
			},
			{
				label: '注册资本',
				key: 'registerCapital',
				tipType: 1,
				required: true
			},
			{
				label: '收款账户名称',
				key: 'bankAccountName',
				tipType: 1,
				required: true
			},
			{
				label: '开户行联行号',
				key: 'cnapsCode',
				tipType: 2,
				required: true
			},
			{
				label: '开户行',
				key: 'bankName',
				labelWidth: 100,
				tipType: 1,
				required: true
			},
			{
				label: '银行账号',
				key: 'bankAccountNo',
				tipType: 1,
				required: true
			},
			{
				label: '公司网址',
				key: 'companyWeb',
				tipType: 1,
				required: false
			},
			{
				label: '物料大类',
				key: 'provisionBroad',
				tipType: 2,
				required: true
			},
			{
				label: '物料小类',
				key: 'provisionSmall',
				tipType: 2,
				required: true
			},
			{
				label: '合作业务',
				key: 'mainBussiness',
				labelWidth: 100,
				tipType: 1,
				required: true
			}
			],
			companyDataInfo: [{
				label: '法人身份证',
				key: 'legalRepresentativeCard',
			},
			{
				label: '营业执照',
				key: 'bussinessLicense',
			},
			{
				label: '供应商资质证书',
				key: 'supplierCertification',
			},
			{
				label: '以往合作合同',
				key: 'cooperativeContract',
			}
			],
			childFields: {
				// 子表字段
				联系人: 'lxr',
				联系电话: 'lxfs',
			},
			scrollTop: 0, // 滚动顶部距离
			maxHeight1: 0,
			maxHeight2: 0,
			maxHeight3: 0,
			maxHeight4: 0,
			uId1: uni.$u.guid(),
			uId2: uni.$u.guid(),
			uId3: uni.$u.guid(),
			uId4: uni.$u.guid(),
			formType: null,
			formType1: null,
			height: 37,
			smallList: [],
			isSubmit: false,
			inRequire: [
				'proposerDeptId',
				'proposer',
				'createTime',
				'enterpriseName',
				'commercialType',
				'enterpriseCreditCode',
				'enterpriseType',
				'legalRepresentative',
				'enterpriseAddress',
				'registerDate',
				'registerCapital',
				'bankName',
				'bankAccountNo',
				'provisionBroad',
				'provisionSmall',
				'mainBussiness',
				// 'legalRepresentativeCard',
				// 'bussinessLicense',
				// 'supplierCertification',
				// 'cooperativeContract',
			],
			isComplete: false,
			showSave: false,
			showDelete: false,
			loading: false,
			id: null,
		}
	},
	components: {
		fileList,
		collapse,
		defaultList,
	},
	computed: {
		...mapState(['userInfo']),
		showEdit() {
			return this.formType === this.APPTYPE.ADD
		},
	},
	onPageScroll(e) {
		this.scrollTop = e.scrollTop
	},
	created() {
		const type = this.formType;
		if (type) {
			if (type === this.APPTYPE.ADD) {
				this.initForm()
			}
			if (type === this.APPTYPE.EDIT) {
				this.showDelete = true
			}
		}
		uni.getSystemInfo({
			success(e) {
				uni.setStorageSync('getSystemInfo', e);
			}
		})
		let safeArea = uni.getStorageSync('getSystemInfo').safeArea.top
		this.height = safeArea + 37
	},
	onReady() {
		this.setCollapseHeight()
	},
	onLoad(options) {
		options && options.isProPayContract?this.isProPayContract = true : this.isProPayContract = false
		options && options.id && this.loadData(options.id);
		this.formType = options.formType || null;
		this.formType1 = options.formType || null;
		var that = this

		uni.$on(that.APPTYPE.CONTACTUNIT, function (data) {
			that.isClick = true
			that.detailData = Object.assign({}, that.detailData, data);
			that.setCollapseHeight()
			that.isComplete = that.formFieldComplete()
		});
		uni.$on(that.APPTYPE.CONTACTS, function (data) {
			that.isClick = true
			that.childTable = data
			that.setCollapseHeight()
			that.isComplete = that.formFieldComplete()
		});
		uni.$on(that.APPTYPE.COMPANYDATA, function (data) {
			that.isClick = true
			that.detailData = Object.assign({}, that.detailData, data);
			that.isComplete = that.formFieldComplete()
		});
	},
	onUnload() {
		uni.$off(this.APPTYPE.CONTACTUNIT);
		uni.$off(this.APPTYPE.CONTACTS);
		uni.$off(this.APPTYPE.COMPANYDATA);
	},
	methods: {
		updatePrevPageList() {
			let pages = getCurrentPages();
			let prevPage = pages[pages.length - 2] //上一页页面实例
			if ('undefined' !== typeof prevPage) {
				// #ifdef APP-PLUS
				prevPage = prevPage.$vm;
				// #endif
				prevPage.getList();
				prevPage.getTotla();
			}
		},
		onClose () {
			uni.navigateBack()
		},
		async onDraft() {
			this.isClick = true
			var that = this
			this.isSubmit = true
			try {
				this.loading = true
				var url = ''
				if (this.id) {
					url = edit
				} else {
					url = add
				}
				const response = await url({
					...this.detailData,
					detailList: this.childTable,
				})
				if (response.success) {
					that.updatePrevPageList()
					that.$refs.uToast.show({
						message: response.message,
						type: 'default',
						complete() {
							uni.navigateBack()
						}
					})
				}
			} finally {
				// this.loading = false
			}
		},
		backStep () {
			if (this.formType1 == 'edit') {
				if (!this.showDelete) {
					this.showDelete = true
					this.formType = this.formType1
				} else {
					uni.navigateBack()
				}
			} else {
				uni.navigateBack()
			}
		},
		async submit() {
			this.isClick = true
			const that = this
			if (that.childListEmpty()) {
				that.$u.toast('请添加联系人信息！');
				return;
			}
			if (!that.formFieldComplete()) {
				that.$u.toast('请填写必填项信息！');
				return;
			}

			that.isSubmit = true
			try {
				var url = ''
				if (this.id) {
					url = edit
				} else {
					url = add
				}
				const response = await url({
					...this.detailData,
					detailList: this.childTable,
				})
				if (response.success) {
					if (this.isProPayContract) {
						this.getSupplierSubmit()
					} else {
						this.onProcess()
					}
					
					// that.updatePrevPageList()
					// that.$refs.uToast.show({
					// 	message: response.message,
					// 	type: 'default',
					// 	complete() {
					// 		uni.navigateBack()
					// 	}
					// })
				}
			} finally {
				// this.loading = false
			}
		},
		async onProcess () {
			var that = this
			try {
				var url = submit
				const response = await url({
					id: that.id
				})
				if (response.success) {
					that.updatePrevPageList()
					that.$refs.uToast.show({
						message: response.message,
						type: 'default',
						complete() {
							uni.navigateBack()
						}
					})
				}
			} finally {
				// this.loading = false
			}
		},
		async getSupplierSubmit () {
			var url = supplierSubmit
			const response = await url({
				id: this.id
			})
			if (response.success) {
				this.updatePrevPageList()
				this.$refs.uToast.show({
					message: response.message || '提交成功',
					type: 'default',
					complete() {
						uni.navigateBack()
					}
				})
			} else {
				this.$refs.uToast.show({
					message: response.message,
					type: 'default'
				})
			}
		},
		onSubmit() {
			const that = this
			uni.showModal({
				content: '确定提交吗',
				success: function (res) {
					if (res.confirm) {
						that.submit();
					}
				}
			});
		},
		onEdit() {
			this.formType = APPTYPE.ADD
			this.showDelete = false
		},
		onDel() {
			let that = this;
			uni.showModal({
				content: '确定删除吗',
				success: function (res) {
					if (res.confirm) {
						deleteData({
							id: that.id
						}).then((res) => {
							if (res.success) {
								that.updatePrevPageList()
								that.$u.toast(res.message);
								if (getCurrentPages().length > 1) {
									uni.navigateBack()
								} else {
									uni.reLaunch({
										url: '/pages/home/home'
									})
								}
							} else {
								that.$u.toast(res.message);
							}
						});
					}
				}
			});
		},
		confirm(data) {
			this.isComplete = false;
			this.showSave = true;
			this.formType = APPTYPE.EDIT
		},
		isNull(value) {
			return value === '' || value === null || value === undefined
		},
		childListEmpty() {
			return this.childTable.length === 0
		},
		formFieldComplete() {
			let isComplete = false;
			const self = this;
			for (let key in self.detailData) {
				if (self.inRequire.includes(key)) {
					if (self.isNull(self.detailData[key])) {
						isComplete = false;
						break;
					} else {
						isComplete = true;
					}
				}
			}
			const empty = self.childListEmpty()
			if (empty) {
				isComplete = !empty
			}
			return isComplete;
			// self.isComplete = isComplete;
		},
		goEdit(tpe) {
			let _url = '';
			switch (tpe) {
				case this.APPTYPE.CONTACTUNIT:
					_url = '/pages/purchase/components/ContactUnitForm?formData=' + encodeURIComponent(JSON.stringify(
						this.detailData))
					break;
				case this.APPTYPE.CONTACTS:
					_url = '/pages/purchase/components/ContactsForm?formData=' + encodeURIComponent(JSON.stringify(
						this.childTable))
					break;
				default:
					_url = '/pages/purchase/components/CompanyDataForm?formData=' + encodeURIComponent(JSON.stringify(
						this.detailData)) + '&companyData=' + encodeURIComponent(JSON.stringify(
							this.companyDataInfo)) + '&title=企业资质材料'
					break;
			}
			uni.navigateTo({
				url: _url
			})
		},
		// 初始化新增需要的数据
		initForm() {
			this.detailData.proposer = this.userInfo.empId //当前登录人
			this.detailData.proposerDeptId = this.userInfo.deptId //当前登录人部门
			this.detailData.createTime = moment().format('YYYY-MM-DD HH:mm:ss')
		},
		findProvisionSmallList(value) {
			const parentId = value
			queryProvisionSmallList({
				parentId
			}).then((res) => {
				if (res.success) {
					const data = res.result.map((item) => {
						return {
							id: item.id,
							categoryName: item.categoryName
						}
					})
					this.smallList = [data]
				} else {
					this.$u.toast(res.message)
				}
			})
		},
		getChildTable(id) {
			childList({
				pageNo: 1,
				pageSize: 100,
				mainId: id,
				column: 'createTime',
				order: 'desc',
				field: 'id',
			}).then((response) => {
				this.childTable = response.result || []
			})
		},
		// 查询预立项申请详情
		loadData(id) {
			this.id = id;
			queryById({
				id
			}).then((res) => {
				if (res.success) {
					this.detailData = res.result
					this.detailData.proposer? this.detailData.proposer :  this.detailData.proposer = this.userInfo.empId //当前登录人
					this.detailData.proposerDeptId? this.detailData.proposerDeptId : this.detailData.proposerDeptId = this.userInfo.deptId //当前登录人部门
					this.$nextTick(function () {
						this.setCollapseHeight(this.detailData.rejectExcuse ? true : false)
					})
					this.$nextTick(() => {
						this.initForm()
					})
					this.getChildTable(this.detailData.id)
				} else {
					this.$refs.uToast.show({
						message: res.message,
						type: 'error',
					})
				}
			})
		},
		setCollapseHeight(reject) {
			this.timer = setTimeout(() => {
				clearTimeout(this.timer)
				this.timer = null
				this.$nextTick(function () {
					uni
						.createSelectorQuery()
						.select('#' + this.uId1)
						.boundingClientRect((data) => {
							this.maxHeight1 = data.height
						})
						.exec()
				})
				this.$nextTick(function () {
					uni
						.createSelectorQuery()
						.select('#' + this.uId2)
						.boundingClientRect((data) => {
							this.maxHeight2 = data.height
						})
						.exec()
				})
				this.$nextTick(function () {
					uni
						.createSelectorQuery()
						.select('#' + this.uId3)
						.boundingClientRect((data) => {
							this.maxHeight3 = data.height
						})
						.exec()
				})
			}, 300)
			// if (reject) {
			// 	this.$nextTick(function () {
			// 		uni
			// 			.createSelectorQuery()
			// 			.select('#' + this.uId4)
			// 			.boundingClientRect((data) => {
			// 				this.maxHeight4 = data.height
			// 			})
			// 			.exec()
			// 	})
			// }
		},
		// 点击tabs
		onTabClick(item) {
			uni
				.createSelectorQuery()
				.in(this)
				.select(`#${item.id}`)
				.boundingClientRect((data) => {
					uni.pageScrollTo({
						scrollTop: data.top + this.scrollTop - 54,
						duration: 150,
					})
				})
				.exec()
		},
	},
}
</script>
<style lang="scss" scoped>
@import '@/pages/synergy/common/actionNew.scss';
@import url('@/assets/inputStyle.scss');

// .task_lists {
// 	padding: 20rpx 20rpx 0;
// }

.file-type {
	margin-top: 20rpx;
	font-size: 14px;
	// font-family: PingFangSC-Regular, PingFang SC;
	font-weight: 400;
	color: #B2B2B2;
}

.file-type-line {
	margin: 20rpx 0 0;
	width: 100%;
	background: rgba(0, 0, 0, 0.1);
	height: 2rpx;
}

.red {
	color: red;
}

.btn-edit {
	padding: 22rpx 0;
	font-size: 14px;
	// font-family: PingFangSC-Regular, PingFang SC;
	font-weight: 400;
	color: #1E6FFF;
	text-align: center;
	border-top: 1rpx solid rgba(0, 0, 0, 0.1);
}

.reject-reason {
	padding: 8px 16px;
}
</style>